<template>
  <a-form
    ref="formRef"
    :model="formData"
    class="form"
    :label-col-props="{ span: 8 }"
    :wrapper-col-props="{ span: 16 }"
  >
    <a-form-item
      field="phone"
      :rules="[
        { required: true, message: $t('login.form.telRequired') },
        {
          match: /^1[3456789]\d{9}$/,
          message: $t('login.form.telInvalid'),
        },
      ]"
      :validate-trigger="['change', 'blur']"
      :label="$t('userSetting.form.phone')"
    >
      <a-input
        v-model="formData.phone"
        :placeholder="$t('login.form.telPlaceholder')"
        :maxlegth="11"
      >
      </a-input>
    </a-form-item>
    <a-form-item
      field="captcha"
      :rules="[{ required: true, message: $t('login.form.captchaRequired') }]"
      :validate-trigger="['change', 'blur']"
      :label="$t('userSetting.form.captcha')"
    >
      <a-input
        v-model="formData.captcha"
        :placeholder="$t('login.form.captchaPlaceholder')"
        :maxlegth="50"
      >
        <template #append>
          <a-button type="text" :loading="smsLoading" @click="getSMSCaptcha">
            <span v-if="countDown === -2" class="captcha-word">{{
              $t('login.form.getCaptcha')
            }}</span>
            <span v-else-if="countDown === -1" class="captcha-word">{{
              $t('login.form.regainCaptcha')
            }}</span>
            <span v-else class="captcha-word">{{ `${countDown}s` }}</span>
          </a-button>
        </template>
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-space>
        <a-button type="primary" :loading="loading" @click="validate">
          {{ $t('userSetting.save') }}
        </a-button>
        <a-button type="secondary" @click="reset">
          {{ $t('userSetting.reset') }}
        </a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { updataPhone, PhoneParams, getPhoneCode } from '@/api/user';
  import { Message } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import { useI18n } from 'vue-i18n';

  const { loading, setLoading } = useLoading();
  const { t } = useI18n();
  const formRef = ref<FormInstance>();
  const formData = ref<PhoneParams>({
    phone: '',
    captcha: '',
  });

  // 处理验证码
  const countDown = ref(-2);
  const smsLoading = ref(false);
  // 存储验证码
  let captchaKey = '';
  const updataCountDown = () => {
    countDown.value = 60;
    const counter = setInterval(() => {
      if (countDown.value === 0) {
        clearInterval(counter);
        countDown.value = -1;
      } else {
        countDown.value--;
      }
    }, 1000);
  };
  const getSMSCaptcha = async () => {
    if (countDown.value >= 0) {
      Message.warning(t('login.form.captchaHoldOn'));
      return;
    }
    const res = await formRef.value?.validateField('phone');
    // 仅判断手机号是否校验通过
    if (res) {
      return;
    }
    smsLoading.value = true;
    try {
      const { data } = await getPhoneCode(formData.value.phone);
      captchaKey = data;
    } catch (err) {
      // you can report use errorHandler or other
      if (typeof err === 'string') {
        Message.error(err);
      }
    } finally {
      smsLoading.value = false;
      updataCountDown();
    }
  };

  const validate = async () => {
    if (loading.value) return;
    const res = await formRef.value?.validate();
    if (!res) {
      setLoading(true);
      try {
        const params: PhoneParams = {
          ...formData.value,
          key: captchaKey,
        };
        const result = await updataPhone(params);
        if (result.status) {
          Message.success(t('userSetting.phone.edit.success'));
        }
      } catch (e: any) {
        // nothing to do here
      } finally {
        setLoading(false);
      }
    }
  };
  const reset = async () => {
    await formRef.value?.resetFields();
  };
</script>

<style scoped lang="less">
  .form {
    width: 540px;
    margin: 0 auto;
    :deep(.arco-form-item-content-flex) {
      justify-content: flex-end;
    }
  }
</style>
